/*
 *@Author: 张楚
 *@Date: 2021-10-13 10:49:30
 *@Description: 选择图片
*/
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http_parser/http_parser.dart';

class ChooseImagePage extends StatefulWidget {
  String title;

  ChooseImagePage({Key key, this.title}) : super(key: key);

  @override
  ImageState createState() => new ImageState(title);
}

class ImageState extends State<ChooseImagePage> {
  final _picker = ImagePicker();
  String title;
  File imagePath;
  String ihh;
  ImageState(this.title);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('$title') ?? '',
      ),
      body: new Column(
        //crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          new RaisedButton(onPressed: openGallery, child: new Text('图库')),
          new RaisedButton(onPressed: takePhotos, child: new Text('拍照')),
          if (imagePath == null)
            new Expanded(child: new Center(child: new Text('未选择图片')))
          else
            new Expanded(
                child: new Center(
              child: Image.file(imagePath),
            )),
          SafeArea(
            child: new RaisedButton(
              onPressed: showPicker,
              child: new Text('上传'),
            ),
          )
        ],
      ),
    );
  }

  void openGallery() async {
    PickedFile pickedFile = await _picker.getImage(source: ImageSource.gallery);
    final File file = File(pickedFile.path);
    setState(() {
      imagePath = file;
    });
  }

  void takePhotos() async {
    PickedFile pickedFile = await _picker.getImage(
      source: ImageSource.camera,
    );
    final File file = File(pickedFile.path);
    setState(() {
      imagePath = file;
    });
  }

  upLoadImg() async {
    if (imagePath == null) {
      showtoast('未选择图片！');
      return;
    }
    String path = imagePath.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formdata = FormData.fromMap(
      {
        "参数名xxx": await MultipartFile.fromFile(path,
            filename: name, contentType: MediaType('image', 'jpeg'))
      },
    );

    BaseOptions option = new BaseOptions(
        contentType: 'multipart/form-data', responseType: ResponseType.plain);

    Dio dio = new Dio(option);
    //application/json
    try {
      var respone =
          await dio.post<String>("后台接口https//xxx.xxx...", data: formdata);
      if (respone.statusCode == 200) {
        showtoast('图片上传成功');
      }
    } catch (e) {
      print("e:" + e.toString() + "   head=" + dio.options.headers.toString());
    }
  }

//弹出选择相册/拍照对话框
  showPicker() {
    //底部弹出
    showModalBottomSheet(
        context: context,
        builder: (BuildContext con) => Container(
              height: 160,
              padding: EdgeInsets.all(20),
              color: Colors.white,
              child: Expanded(
                child: ListView(
                  children: [createItem(true, "拍照"), createItem(false, "相册")],
                ),
              ),
            ));
  }

//创建item
  Widget createItem(bool state, String name) {
    return GestureDetector(
        onTap: () {
          //点击事件处理
          openPicker(state);
        },
        child: ListTile(
          leading: Icon(state ? Icons.camera : Icons.image),
          title: Text(name),
        ));
  }

//使用imagePicker异步打开拍照 、相册
  openPicker(bool state) async {
    //销毁底部弹出框
    Navigator.pop(context);
    var picker = ImagePicker();
    //根据状态标识决定打开相机还是相册
    var future = await picker.getImage(
        source: state ? ImageSource.camera : ImageSource.gallery);
    setState(() {
      //通过setstate 通知重绘更新
      imagePath = File(future.path);
    });
  }

  void showtoast(String toast) {
    Fluttertoast.showToast(
        msg: toast, gravity: ToastGravity.BOTTOM, textColor: Colors.grey);
  }
}
